import twisted.internet.protocol
from twisted.internet import reactor

class Chat(twisted.internet.protocol.Protocol):
	def __init__(self, factory):
		self.factory = factory
		self.id = 0

	def getIndex(self):
		return self.index

	def connectionMade(self):
		print "hello, %s ins coming" % self.id
		self.factory.sendAll("hello, %s ins coming" % self.id)

	def connectionLost(self, reason):
		print "hello, %s ins bye" % self.id
		self.factory.sendAll("hello, %s ins bye" % self.id)

	def dataReceived(self, data):
		uid, srvid, funid = getPacketInfo();
		if self.index == 0 :
			uid = getIndexId()
			self.index = uid
			self.factory.addClient(self.index)
		srv = getSrvInfo(srvid)
		srv.call(funid)
		pass

class ChatFactory(twisted.internet.protocol.Factory):
	def __init__(self):
		self.users = {}

	def buildProtocol(self, addr):
		c = Chat(self)
		return c

	def addClient(self, client):
		self.users[client.index] = client

	def delClient(self, client):
		if client.index in self.users:
			del self.users[client.index]

	def sendAll(self, data):
		for key in self.users:
			self.users[key].transport.write(data)

	def sendToClient(self, index, data):
		to = self.user[index]
		to.transport.write(data)

reactor.listenTCP(8888, ChatFactory())
reactor.run()